package userFileModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"KumquatDrivesServices/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"time"
)

type removeFilesRequest struct {
	FileIds []model.SnowflakeIdType `json:"fileIds"`
}

func (UserFileModuleApi) RemoveFiles(c *gin.Context) {
	var req removeFilesRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		logrus.Errorf("ShouldBindJSON err: %v", err)
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	userId := utils.GetUserId(c)
	var originalFileInfos []model.FileModel
	query := global.DB.Where("id in (?) and user_id =? and del_flag=?", req.FileIds, userId, enums.Normal)
	if err := query.Find(&originalFileInfos).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.Errorf("FindFileInfos err: %v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if len(originalFileInfos) == 0 {
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	updateMap := map[string]any{
		"del_flag":      enums.RecycleBin,
		"recovery_time": time.Now().Unix(),
	}
	//开启事务将状态修改为回收站
	tx := global.DB.Begin()
	var deleteFileOfFolderIds []model.SnowflakeIdType
	for _, fileInfo := range originalFileInfos {
		if fileInfo.IsFolder == enums.File {
			deleteFileOfFolderIds = append(deleteFileOfFolderIds, fileInfo.ID)
			continue
		}
		//将选中的文件夹标记为回收站并将其下的文件全部标记为禁用
		var deleteChildrenFileOfFolderIds []model.SnowflakeIdType
		result, err := utils.FindAllSubFolderFileList(userId, fileInfo.ID, enums.Normal)
		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			logrus.Errorf("FindFileInfos err: %v", err)
			res.FailWithCode(res.SYS_ERR, c)
			return
		}
		for _, v := range result {
			deleteChildrenFileOfFolderIds = append(deleteChildrenFileOfFolderIds, v.ID)
		}
		if len(deleteChildrenFileOfFolderIds) > 0 {
			//将其下的文件全部标记为禁用
			updateQuery := tx.Model(&model.FileModel{}).Where("id in (?) and user_id=? and del_flag=?", deleteChildrenFileOfFolderIds, userId, enums.Normal)
			if err = updateQuery.Update("del_flag", enums.Forbidden).Error; err != nil {
				tx.Rollback()
				logrus.Errorf("updateQuery.Updates err: %v", err)
				res.FailWithCode(res.SYS_ERR, c)
				return
			}
		}
		//将选中的文件夹放到deleteFileOfFolderIds中后续统一更改状态
		deleteFileOfFolderIds = append(deleteFileOfFolderIds, fileInfo.ID)
	}
	// 更新所有需要放入回收站的文件或文件夹的状态为回收站
	if len(deleteFileOfFolderIds) == 0 {
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	updateQuery := tx.Model(&model.FileModel{}).Where("id in (?) and user_id=? and del_flag=?", deleteFileOfFolderIds, userId, enums.Normal)
	if err := updateQuery.Updates(updateMap).Error; err != nil {
		tx.Rollback()
		logrus.Errorf("updateQuery.Updates err: %v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		logrus.Errorf("Commit err: %v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	res.OkWithData(res.EmptyData, c)
}
